package com.ttn.auth.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ttn.auth.openfeign.StudentRecordFeignService;
import com.ttn.auth.service.SysUserService;
import com.ttn.common.core.entity.Result;
import com.ttn.common.core.entity.auth.SysUser;
import com.ttn.common.core.entity.auth.bo.SysUserLoginBO;
import com.ttn.common.core.entity.auth.bo.WechatLoginBO;
import com.ttn.common.core.entity.studentrecord.StudentRecord;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("/auth")
public class UserLoginController {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private StudentRecordFeignService studentRecordFeignService;
    @Resource
    private WxMaService wxMaService;

    /**
     * 系统用户登录
     *
     * @param sysUserLoginBO
     * @return
     */

    @PostMapping("/query/sys-user-login")
    public Result querySysUserLogin(@RequestBody SysUserLoginBO sysUserLoginBO) {
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(SysUser::getPassword, sysUserLoginBO.getPassword()).and(sysUserLambdaQueryWrapper1 -> {
            sysUserLambdaQueryWrapper1.eq(SysUser::getUserName, sysUserLoginBO.getLoginName()).or().eq(SysUser::getMobile,
                    sysUserLoginBO.getLoginName());
        });
        SysUser loginSysUser = sysUserService.getOne(sysUserLambdaQueryWrapper);
        if (Objects.nonNull(loginSysUser)) {
            StpUtil.login(loginSysUser.getId(), "PC");
            return Result.success(StpUtil.getTokenInfo());
        }
        return Result.fail("账号密码错误，请检查后重试");
    }

//    @PostMapping("/query/student-login")
//    public Result queryStudentLogin(@RequestBody SysUserLoginBO sysUserLoginBO) {
//        Result<StudentRecord> studentRecordResult = studentRecordFeignService.serviceQueryStudentLogin(sysUserLoginBO.getLoginName());
//        if (studentRecordResult.isSuccess()) {
//            StpUtil.login(studentRecordResult.getData().getId(), "WX");
//            return Result.success(StpUtil.getTokenInfo());
//        }
//        return Result.fail("账户不存在，请确认后重试");
//    }

    @PostMapping("/query/wechat-login")
    public Result queryWechatLogin(@RequestBody WechatLoginBO wechatLoginBO) {
        log.info("UserLoginController queryWechatLogin ,参数:{}", wechatLoginBO);
        WxMaJscode2SessionResult sessionInfo = null;
        WxMaUserInfo WxMaUserInfo = null;
        WxMaPhoneNumberInfo wxMaPhoneNumberInfo = null;
        StudentRecord studentRecord = new StudentRecord();
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(wechatLoginBO.getCode());
            log.info("sessionInfo;{}", sessionInfo);
            Result<StudentRecord> resultStudentRecord =
                    studentRecordFeignService.queryStudentRecordByOpenId(sessionInfo.getOpenid());
            if (resultStudentRecord.isSuccess() && Objects.nonNull(resultStudentRecord.getData()) && Objects.nonNull(resultStudentRecord.getData().getId())) {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                StpUtil.login(resultStudentRecord.getData().getId(), "wx");
                resultMap.put("tokenInfo", StpUtil.getTokenInfo());
                resultMap.put("sessionKey", sessionInfo.getSessionKey());
                log.info("登录成功返回;{}", sessionInfo);
                return Result.success(resultMap);
            }
            WxMaUserInfo = wxMaService.getUserService().getUserInfo(sessionInfo.getSessionKey(),
                    wechatLoginBO.getUserEncryptedData(),
                    wechatLoginBO.getUserIv());
            log.info("WxMaUserInfo;{}", WxMaUserInfo);
            studentRecord.setNickName(WxMaUserInfo.getNickName());
//            studentRecord.setLastLogin(DateTime.now());
            studentRecord.setOpenId(sessionInfo.getOpenid());
            studentRecord.setUnionId(WxMaUserInfo.getUnionId());
            studentRecord.setAvatarUrl(WxMaUserInfo.getAvatarUrl());
            studentRecord.setGender(Integer.valueOf(WxMaUserInfo.getGender()));
            wxMaPhoneNumberInfo =
                    wxMaService.getUserService().getPhoneNoInfo(sessionInfo.getSessionKey(),
                            wechatLoginBO.getEncryptedData(), wechatLoginBO.getIv());
            log.info("wxMaPhoneNumberInfo;{}", wxMaPhoneNumberInfo);
            studentRecord.setCellPhoneNumber(wxMaPhoneNumberInfo.getPhoneNumber());
            log.info("studentRecord;{}", studentRecord);
            Result<StudentRecord> result = studentRecordFeignService.serviceQueryStudentLogin(studentRecord);
            log.info("result;{}", result);
            if (result.isSuccess()) {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                StpUtil.login(result.getData().getId(), "wx");
                resultMap.put("tokenInfo", StpUtil.getTokenInfo());
                resultMap.put("sessionKey", sessionInfo.getSessionKey());
                return Result.success(resultMap);
            } else {
                return Result.fail(result.getMsg());
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/query/wechat-login-new")
    public Result queryWechatLoginNew(@RequestBody WechatLoginBO wechatLoginBO) {
        WxMaJscode2SessionResult sessionInfo = null;
        WxMaPhoneNumberInfo wxMaPhoneNumberInfo = null;
        StudentRecord studentRecord = new StudentRecord();
        studentRecord.setOpenId("测试123456");
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(wechatLoginBO.getCode());
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        log.info("sessionInfo;{}", sessionInfo);
        wxMaPhoneNumberInfo =
                wxMaService.getUserService().getPhoneNoInfo(sessionInfo.getSessionKey(),
                        wechatLoginBO.getEncryptedData(),
                        wechatLoginBO.getIv());

        log.info("wxMaPhoneNumberInfo1;{}", wxMaPhoneNumberInfo);
//        studentRecord.setLastLogin(DateTime.now());
        log.info("studentRecord;{}", studentRecord);
        Result<StudentRecord> result = studentRecordFeignService.serviceQueryStudentLogin(studentRecord);
        log.info("result;{}", result);
        if (result.isSuccess()) {
            SaLoginModel saLoginModel = new SaLoginModel();
            saLoginModel.setDevice("wx");
            saLoginModel.setExtra("a", "a");
            StpUtil.login(result.getData().getId(), saLoginModel);

            return Result.success(StpUtil.getTokenInfo());
        } else {
            return Result.fail(result.getMsg());
        }

    }

}
